package com.lvbaoins.creditapp.util;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.InputStreamBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.util.List;
import java.util.Map;

public class HttpClient {

    static Logger logger = LoggerFactory.getLogger(HttpClient.class);

    /**
     * get请求
     *
     * @return
     */
    public static String doGet(String url) {
        CloseableHttpClient httpCilent = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(url);
        CloseableHttpResponse response = null;
        String res = null;
        try {
            response = httpCilent.execute(httpGet);
            StatusLine status = response.getStatusLine();
            int state = status.getStatusCode();
            HttpEntity responseEntity = response.getEntity();
            res = EntityUtils.toString(responseEntity);
            if (state != 200) {
                System.out.println("请求返回:" + state + " " + res + "(" + url + ")");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            try {
                httpCilent.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return res;
    }

    public static String doGet(String url, Map<String, Object> param) {

        // 创建Httpclient对象
        CloseableHttpClient httpclient = HttpClients.createDefault();

        String resultString = "";
        CloseableHttpResponse response = null;
        try {
            // 创建uri
            URIBuilder builder = new URIBuilder(url);
            if (param != null) {
                for (String key : param.keySet()) {
                    builder.addParameter(key, (String) param.get(key));
                }
            }
            URI uri = builder.build();

            // 创建http GET请求
            HttpGet httpGet = new HttpGet(uri);

            // 执行请求
            response = httpclient.execute(httpGet);
            // 判断返回状态是否为200
            if (response.getStatusLine().getStatusCode() == 200) {
                resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return resultString;
    }


    /**
     * post请求
     *
     * @param url
     * @param param
     * @return
     */
    public static String doPost(String url, Map<String, Object> param) {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        HttpPost httpPost = null;
        try {
            // 创建Http Post请求
            httpPost = new HttpPost(url);
            RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(10000).setConnectionRequestTimeout(10000).setSocketTimeout(1000*60).build();
            httpPost.setConfig(requestConfig);
            // 创建参数列表
            if (param != null) {
                StringEntity entity = new StringEntity(JSONObject.toJSONString(param), "UTF-8");
                entity.setContentType("application/json");
                entity.setContentEncoding("utf-8");
                httpPost.setEntity(entity);
            }
            // 执行http请求
            response = httpClient.execute(httpPost);
            String resultString = EntityUtils.toString(response.getEntity(), "utf-8");
            return resultString;
        } catch (Exception e) {
            logger.error("[http连接失败:]", e);
        } finally {
            if (httpPost != null) {
                httpPost.releaseConnection();
            }
            try {
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                logger.error("[http连接失败:]", e);
            }
            if (httpClient != null) {
                try {
                    httpClient.close();
                } catch (IOException e) {
                    logger.error("[http连接失败:]", e);
                }
            }
        }

        return null;
    }

    /**
     * @Title: doPost
     * @Description: post请求
     * @param: url
     * @param: params
     * @return: String
     */
    public static String doPost(String url, JSONObject json) {

        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        String charSet = "UTF-8";
        StringEntity entity = new StringEntity(json.toJSONString(), charSet);
        entity.setContentEncoding(charSet);
        entity.setContentType("application/json");
        httpPost.setEntity(entity);
        CloseableHttpResponse response = null;
        String res = null;
        try {
            response = httpclient.execute(httpPost);
            StatusLine status = response.getStatusLine();
            int state = status.getStatusCode();
            HttpEntity responseEntity = response.getEntity();
            res = EntityUtils.toString(responseEntity);
            if (state != 200) {
                System.out.println("请求返回:" + state + " " + res + "(" + url + ")");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            try {
                httpclient.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return res;
    }

    /**
     * @Title: doPost
     * @Description: post请求
     * @param: url
     * @param: urlParameters
     * @return: String
     */
    public static String doPost(String url, List<NameValuePair> urlParameters) {

        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        String charSet = "UTF-8";
        try {
            httpPost.setEntity(new UrlEncodedFormEntity(urlParameters, charSet));
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        }
        CloseableHttpResponse response = null;
        String res = null;
        try {
            response = httpclient.execute(httpPost);
            StatusLine status = response.getStatusLine();
            int state = status.getStatusCode();
            HttpEntity responseEntity = response.getEntity();
            res = EntityUtils.toString(responseEntity);
            if (state != 200) {
                System.out.println("请求返回:" + state + " " + res + "(" + url + ")");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            try {
                httpclient.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return res;
    }

    public static String doPostStream(String url, Map<String, String> param, Map<String, InputStream> streamMap) {
        // MultipartEntityBuilder;
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);
            // 创建参数列表
            MultipartEntityBuilder meBuilder = MultipartEntityBuilder.create();
            if (param != null) {
                for (String key : param.keySet()) {
                    meBuilder.addPart(key, new StringBody((String) param.get(key), ContentType.APPLICATION_JSON));
                }
            }
            if (streamMap != null) {
                for (String key : streamMap.keySet()) {
                    InputStreamBody inputStreamBody = new InputStreamBody(streamMap.get(key), key);
                    meBuilder.addPart(key, inputStreamBody);
                }
            }
            HttpEntity entity = meBuilder.build();
            httpPost.setEntity(entity);
            // 执行http请求
            response = httpClient.execute(httpPost);
            resultString = EntityUtils.toString(response.getEntity(), "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return resultString;
    }

}
